package net.diaowen.dwsurvey.controller;

import net.diaowen.common.plugs.page.Page;
import net.diaowen.common.utils.SystemUtils;
import net.diaowen.dwsurvey.entity.LotteryActivity;
import net.diaowen.dwsurvey.entity.LotteryPrize;
import net.diaowen.dwsurvey.entity.SurveyDirectory;
import net.diaowen.dwsurvey.service.LotteryActivityManager;
import net.diaowen.dwsurvey.service.LotteryPrizeManager;
import net.diaowen.dwsurvey.service.SurveyDirectoryManager;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/sy/lottery/")
public class LotteryActivityController {

    @Autowired
    private LotteryActivityManager lotteryActivityManager;

    @Autowired
    private LotteryPrizeManager lotteryPrizeManager;

    @Autowired
    private SurveyDirectoryManager surveyDirectoryManager;

    @RequestMapping("/list.do")
    public ModelAndView list(HttpServletRequest request, Page<LotteryActivity> page) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        try {
            LotteryActivity entity = new LotteryActivity();
            page = lotteryActivityManager.findPage(page, entity);
            modelAndView.addObject("page", page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        modelAndView.setViewName("/diaowen-lottery/list");
        return modelAndView;
    }


    /**
     * 问卷添加小组
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @RequestMapping("/save.do")
    public String save(LotteryActivity entity) throws Exception {
        try{
            String id = entity.getId();
            if(id==null || id.equals("")){
                entity.setId(null);
                lotteryActivityManager.save(entity);
            }else{
                LotteryActivity lt = lotteryActivityManager.get(id);
                lt.setDescription(entity.getDescription());
                lt.setStartTime(entity.getStartTime());
                lt.setEndTime(entity.getEndTime());
                lt.setName(entity.getName());
                lotteryActivityManager.save(entity);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:/sy/lottery/list.do";
    }
    @RequestMapping("/codeUpload.do")
    @ResponseBody
    public String codeUpload(String id,HttpServletRequest request, HttpServletResponse response ) throws IOException {
        //字符判断:成功传过去lotteryActivity的id,失败传过去1
        System.out.println("进入了codeUpload");
        // System.out.println("id = " + id);
        ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        MultipartHttpServletRequest multiRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest());
        //判断 request 是否有文件上传,即多部分请求
        System.setProperty("sun.jnu.encoding","utf-8");
        //转换成多部分request,取得request中的所有文件名
        Iterator<String> iter = multiRequest.getFileNames();
        MultipartFile file = multiRequest.getFile(iter.next());
        // System.out.println("Filename() = " + file.getOriginalFilename());
        String path = File.separator + "WxCode"+ File.separator + file.getOriginalFilename();
        LotteryActivity lotteryActivity = new LotteryActivity();
        if (file.isEmpty())
        {
            response.getWriter().write("1");
            return null;
        }else{
            if (id.length()!=0)
            {
                lotteryActivity = lotteryActivityManager.get(id);
                File oldFile = new File(System.getProperty("user.home") + File.separator+lotteryActivity.getWxQRcode());
                if (oldFile.exists())
                {
                    oldFile.delete();
                }
                System.out.println("oldFile删除完毕");
            }
            AddWxImg(file);
            lotteryActivity.setWxQRcode(path);//路径
            lotteryActivityManager.save(lotteryActivity);
            response.getWriter().write(lotteryActivity.getId());
            return null;
        }

    }

    private void AddWxImg(MultipartFile wxQRcodefile) {
        System.out.println("进入文件上传");
        String ImgPath = System.getProperty("user.home") + File.separator + "WxCode";
        File file = new File(ImgPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String myFileName = wxQRcodefile.getOriginalFilename();
        String RealPath = ImgPath + File.separator + myFileName;
        System.out.println("RealPath = " + RealPath);
        if (StringUtils.isNotBlank(wxQRcodefile.getOriginalFilename()) != false) {
            try {
                wxQRcodefile.transferTo(new File(RealPath));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/input.do")
    public ModelAndView input(String id) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        if (id != null) {
            LotteryActivity entity = lotteryActivityManager.getModel(id);
            modelAndView.addObject("entity", entity);
            String ImgBase64 = SystemUtils.fileToBase64(System.getProperty("user.home") + entity.getWxQRcode());
            modelAndView.addObject("ImgBase64", ImgBase64);
            System.out.println("修改页面中的ImgBase64" + ImgBase64);
        }
        modelAndView.setViewName("/diaowen-lottery/input");
        return modelAndView;
    }


    // 关联问卷
    @RequestMapping("/surveylist.do")
    public ModelAndView list(HttpServletRequest request, String surveyName, String activityId) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        try {
            List<SurveyDirectory> surveyList = surveyDirectoryManager.findSurveyList(surveyName);
            modelAndView.addObject("surveyList", surveyList);
            String bindSurveyId = lotteryActivityManager.get(activityId).getSurveyId();
            if (bindSurveyId == null) {
                bindSurveyId = "";
            }
            modelAndView.addObject("bindSurveyId", bindSurveyId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        modelAndView.addObject("activityId", activityId);
        modelAndView.setViewName("/diaowen-lottery/survey-list");
        return modelAndView;
    }

    @RequestMapping("/bindSurveyAjax.do")
    @ResponseBody
    public String bindSurvey(HttpServletRequest request, HttpServletResponse response, String surveyId, String activityId) throws IOException {
        String result = lotteryActivityManager.bindSurvey(activityId, surveyId);
        response.getWriter().write(result);
        return null;
    }


    // 删除的方法
    @RequestMapping("/removeActivityAjax.do")
    @ResponseBody
    public String removeActivity(HttpServletRequest request, HttpServletResponse response, String id) throws IOException {
        //如果已经有人过来参加了，那么无法删除
        LotteryActivity lotteryActivity = lotteryActivityManager.get(id);
        String surveyId = lotteryActivity.getSurveyId();
        String wxImgPath = System.getProperty("user.home") + lotteryActivity.getWxQRcode();
        File file = new File(wxImgPath);
        if (surveyId != null) {
            if (lotteryActivityManager.isStart(surveyId)) {
                response.getWriter().write("0");
                return null;
            } else {
                if (file.exists()) {
                    file.delete();
                }
                lotteryActivityManager.delete(id);
                response.getWriter().write("1");
                return null;
            }
        } else {
            if (file.exists()) {
                file.delete();
            }
            lotteryActivityManager.delete(id);
            response.getWriter().write("1");
            return null;
        }
    }

    @RequestMapping("/checkActivityStatusAjax.do")
    @ResponseBody
    public String checkActivityStatus(HttpServletRequest request, HttpServletResponse response, String id) throws IOException {
        // 2--没人参加抽奖，已关联问卷
        // 1--已经有人参加抽奖
        // 0--没人参加抽奖，未关联问卷
        LotteryActivity lotteryActivity = lotteryActivityManager.get(id);
        String surveyId = lotteryActivity.getSurveyId();
        if (lotteryActivityManager.isStart(surveyId)) {
            response.getWriter().write("1");
            return null;
        } else {
            if (lotteryActivity.getSurveyId() == null) {
                response.getWriter().write("0");
            } else {
                response.getWriter().write("2");
            }
            return null;
        }
    }


    @RequestMapping("/checkSurveyStatusAjax.do")
    @ResponseBody
    public String checkSurveyStatus(HttpServletRequest request, HttpServletResponse response, String surveyId) throws IOException {
        // 0 未关联问卷
        // 1关联问卷，但是未设置奖项
        // 2关联问卷，设置了奖项
        LotteryActivity la = lotteryActivityManager.getBySurveyId(surveyId);
        if (la == null) {
            response.getWriter().write("0");
            return null;
        }
        LotteryPrize lp = lotteryPrizeManager.getByActivityId(la.getId());
        if (lp == null) {
            response.getWriter().write("1");
        } else {
            response.getWriter().write("2");
        }
        return null;

    }
}
